<?php

namespace App\Http\Controllers\Api;

use App\Events\GoodsWatched;
use App\Http\Controllers\Controller;
use App\Http\Queries\GoodsSingleQuery;
use App\Http\Resources\GoodsResource;
use App\Http\Resources\GoodsSingleResource;
use Illuminate\Http\Request;
use App\Http\Queries\GoodsQuery;
class GoodsController extends Controller
{
    public function index(Request $request,GoodsQuery $query){
//        dd($query);
//        dd($request->getClientIp());
        $goods_category_id = $request->goods_category_id;
        $page_size = $request->page_size?$request->page_size:10;
        $long_title = $request->long_title;
        $seckill = $request->seckill;
        $hot = boolval($request->hot);
        $recommend = boolval($request->recommend);
        $is_new = boolval($request->is_new);
        $can_i = boolval($request->can_i);
        $myintegral = intval($request->myintegral);
        $order = $request->order;
//        dd($recommend);
        if ($goods_category_id){
            $query->where("goods_category_id",$goods_category_id);
        }
        //秒杀
        if ($seckill){
            $query->where("is_seckill",$seckill);
        }else{
            $query->where("is_seckill",0);
        }

        //阁主推荐不分是否促销
//        dd($recommend);
        if ($recommend){
            $query->where("is_recommend",1);
        }else{
            //促销
            if ($hot){
                //可用积分兑换并且没有参与秒杀的
                //特惠里展示（积分商城的特产）
                $query->where("integral",">",0)
                    ->where("is_seckill",false);
//                $query->where("is_hot",$hot);
            }else{
//                $query->where("integral",0)->orWhere("integral",null);
//                $query->where("is_hot",0);
                $query->where(function ($query){
                    $query->where("integral",0)
                          ->orWhereNull("integral");
                });
            }
        }
        if ($is_new){
            $query->where("is_new",1);
        }
        if ($long_title){
            $query->where("name","like","%".$long_title."%");
        }
        //我是否能换的起
        //因为积分商城可能是未登陆用户可看，因此这里直接传积分判断，无关痛痒，可从前端获取数值
        if ($can_i){
            $query->where("integral","<=",$myintegral);
        }
        if ($order){
            $order_arr = explode(",",$order);
            $query->orderBy($order_arr[0],$order_arr[1]);
//            dd($order_arr);
        }
        $goods_list = $query->orderBy("order_number",'asc')->orderBy("goods_category_id")->paginate($page_size);
//        $query->dump();
        //        dd($goods_list);
        return GoodsResource::collection($goods_list);
    }

//
    public function show($goodsId,GoodsSingleQuery $query,Request $request){
        $goods = $query->findOrFail($goodsId);
        $user = $request->user();
//        |ip = $request->getClientIp();
        //产品点击的响应事件
        event(new GoodsWatched($goods,$request,$user));
        return new GoodsSingleResource($goods);
    }

}
